import React, { useEffect, useState } from 'react'
import { Typography, Button, Form, Input, Space, message } from 'antd'
import type { FormProps } from 'antd'
import style from './index.module.scss'
import { LockOutlined, NumberOutlined, UserOutlined } from '@ant-design/icons'
import { reqCreateCaptcha, reqLogin } from '@/api/login'
import { LoginData, LoginResponseData } from '@/api/login/type'
import { useSetLocalStorage } from '@/hooks/useLocalStorage'
import { MENU, TOKEN } from '@/common/constant'
import { useNavigate } from 'react-router-dom'
import { useDispatch } from 'react-redux'
import { setToken, setUserInfo } from '@/store/modules/user'
import { setMenuList } from '@/store/modules/menu'
const { Title } = Typography
type FieldType = LoginData

const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
  console.warn('表单校验失败:', errorInfo.errorFields)
}

const Login: React.FC = () => {
  // 二维码图片
  const [captchaImg, setCaptchaImg] = useState<string>('')

  // 获取验证码接口
  const getCaptchaImg = async () => {
    let res: string = await reqCreateCaptcha()
    setCaptchaImg(res)
  }

  useEffect(() => {
    getCaptchaImg()
  }, [])

  const dispatch = useDispatch()
  const navigateTo = useNavigate()

  // 表单登录成功接口
  const onFinish: FormProps<FieldType>['onFinish'] = async (values) => {
    let res: LoginResponseData = await reqLogin(values)
    if (res.status === 200) {
      message.success(res.data.message)
      const { token, userInfo, menu } = res.data
      const setData = { token, userInfo }
      // 存储到本地
      useSetLocalStorage(TOKEN, JSON.stringify(setData))
      useSetLocalStorage(MENU, JSON.stringify(menu))
      // 存redux
      dispatch(setUserInfo(userInfo))
      dispatch(setToken(token))
      dispatch(setMenuList(menu))
      // 页面跳转
      navigateTo('/')
    } else if (res.status === 400) {
      getCaptchaImg()
      message.error(res.data.message)
    }
  }

  return (
    <>
      <div className={style.container}>
        <div className='flex-1 h-full flex justify-center items-center scale-x-[-1]'>
          <img
            src='./images/login.png'
            alt=''
          />
        </div>
        <div className='flex-1 h-full flex justify-center items-center'>
          <div className={style.card}>
            <Title
              level={3}
              className={style.title}
            >
              歪fChat后台管理系统
            </Title>
            <Form
              layout='horizontal'
              style={{ width: 'auto' }}
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
            >
              <Form.Item<FieldType>
                name='phone'
                rules={[{ required: true, message: '账号名不能为空' }]}
              >
                <Input
                  placeholder='请输入账号'
                  prefix={
                    <UserOutlined
                      style={{ color: 'rgba(0,0,0,.25)', marginRight: 5 }}
                    />
                  }
                />
              </Form.Item>
              <Form.Item<FieldType>
                name='password'
                rules={[{ required: true, message: '密码不能为空' }]}
              >
                <Input.Password
                  placeholder='请输入密码'
                  prefix={
                    <LockOutlined
                      style={{ color: 'rgba(0,0,0,.25)', marginRight: 5 }}
                    />
                  }
                />
              </Form.Item>
              <Form.Item<FieldType>
                name='captcha'
                rules={[
                  { required: true, min: 4, max: 4, message: '验证码必须是4位' }
                ]}
              >
                <Space direction='horizontal'>
                  <Input
                    placeholder='请输入验证码'
                    prefix={
                      <NumberOutlined
                        style={{ color: 'rgba(0,0,0,.25)', marginRight: 5 }}
                      />
                    }
                  />
                  <div
                    onClick={getCaptchaImg}
                    className='w-[80px] h-[32px] bg-white rounded-md cursor-pointer text-xs flex justify-center items-center'
                  >
                    {captchaImg ? (
                      <div dangerouslySetInnerHTML={{ __html: captchaImg }} />
                    ) : (
                      '加载失败'
                    )}
                  </div>
                </Space>
              </Form.Item>
              <Form.Item>
                <Button
                  type='primary'
                  htmlType='submit'
                  style={{ width: '100%' }}
                >
                  登陆
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>
      </div>
    </>
  )
}

export default Login
